<?php

declare(strict_types=1);

namespace App\Master\Framework\Library\JunZiQian;


use App\Master\Framework\Extend\Module;
use App\Master\Framework\Library\Library;

/**
 * 人脸核身 等
 */
class SignLibrary extends Library
{
    protected string $base_uri = 'https://api.junziqian.com';
    protected array  $config   = [];

    /**
     * 实例化
     */
    public function __construct()
    {
        // 君子签开发配置
        $config = Module::_SetupModule("JzqConfig") ?? [];
        $this->config = [
            'app_key'     => $config['app_key'],
            'app_secret'  => $config['app_secret'],
            'template_no' => $config['template_no'],// 合同模版编号
        ];
    }

    /**
     * 合同签约
     * @param array $params
     * @return bool|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function apply(array $params)
    {
        $signatories = [
            [
                'fullName'     => $params['fullName'],// 出借人
                'identityType' => 1,
                'identityCard' => $params['identityCard'],
                'mobile'       => 15888888888,
                'chapteJson'   => [
                    [
                        'page' => -1, 'chaptes' => [['offsetX' => 0.3, 'offsetY' => 0.67]]
                    ]
                ],
                'noNeedVerify' => 1,
            ],
            [
                'fullName'     => $params['fullName'],// 借款人
                'identityType' => 1,
                'identityCard' => $params['identityCard'],
                'mobile'       => 15888888888,
                'chapteJson'   => [
                    [
                        'page' => -1, 'chaptes' => [['offsetX' => 0.3, 'offsetY' => 0.62]]
                    ]
                ],
                'noNeedVerify' => 1,
            ]
        ];
        // 合同模版自定义的参数
        $templateParams = [
            'order'      => $params['contract_no'],// 合同编号
        ];
        $data = [
            'contractName'   => '合同名称',
            'signatories'    => json_encode($signatories),
            'serverCa'       => 1,
            'dealType'       => 1,
            'templateNo'     => $this->config['template_no'],
            'templateParams' => json_encode($templateParams),
            'fileType'       => 2
        ];
        if (!$this->fillSign($data)){
            return $this->error($this->getMessage());
        }
        $data = $this->getData();
        $response = $this->post("/v2/sign/applySign",$data);
        if ($response->getStatusCode() != 200) {
            return $this->error($response->getReasonPhrase());
        }

        $json = $response->getBody()->getContents();
        $body = json_decode($json,true);
        if (!isset($body['success']) || $body['success'] != true) {
            return $this->error(!empty($body['msg']) ? $body['msg'] : 'Error_0', $body ?? []);
        }

        return $this->success('success',$body);
    }

    /**
     * 填充签名数据
     * @param array $req
     * @param string $encryptMethod
     * @param int $tsType
     * @return bool
     */
    private function fillSign(array $req, string $encryptMethod = 'sha256', int $tsType = 1)
    {
        if (!in_array($encryptMethod, ['sha256', 'md5', 'sha1'])) {
            return $this->error("encryMethod,必须为md5,sha1,sha256之一");
        }

        $ts = time();
        if ($tsType == 1) {
            $ts = $ts * 1000;
        }
        $nonce   = md5((string)$ts);
        $signSrc = "nonce{$nonce}ts{$ts}app_key{$this->config['app_key']}app_secret{$this->config['app_secret']}";

        $sign = match ($encryptMethod) {
            'sha256' => hash($encryptMethod, $signSrc),
            'sha1'   => sha1($signSrc),
            default  => md5($signSrc)
        };

        $req['ts']           = $ts;
        $req['app_key']      = $this->config['app_key'];
        $req['sign']         = $sign;
        $req['nonce']        = $nonce;        //这只是为了生成一个随机值
        $req['encry_method'] = $encryptMethod;//为''也不能传
        return $this->success("success", $req);
    }

}